﻿using System;
using System.Net;
using System.Windows;
using System.Text;
using Microsoft.Phone.Info;
using System.Reflection;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Linq;

namespace MobiSms.Library.Helpers
{
    public class LogHelper
    {
        WebClient client = new WebClient();

        public LogHelper() { }

        public LogHelper(Exception ex)
        {
            this.Exception = ex;
        }

        public DateTime Time { get { return DateTime.Now; } }

        public string TimeSpan
        {
            get { return System.TimeSpan.FromTicks(DateTime.Now.Ticks).ToString(); }
        }
        
        public Exception Exception { get; set; }

        public string Content
        {
            get
            {
                StringBuilder builder = new StringBuilder();

                builder.Append(Time.ToString());
                builder.Append("\r\n\r\n");
                builder.Append(TimeSpan);
                builder.Append("\r\n\r\n");
                builder.Append("\r\n\r\n");

                builder.Append("Exception\r\n\r\n");
                builder.Append("**********\r\n\r\n");
                builder.Append(Exception.Message);
                builder.Append("\r\n\r\n**********\r\n\r\n");
                builder.Append(Exception.StackTrace);
                builder.Append("\r\n\r\n**********\r\n\r\n");
                builder.Append(Exception.GetType().FullName);
                builder.Append("\r\n\r\n**********\r\n\r\n");
                builder.Append(Exception.GetType().Assembly.FullName);
                builder.Append("\r\n\r\n**********\r\n\r\n");


                foreach (object o in this.Exception.Data.Keys)
                {
                    builder.Append(Exception.Data[o].ToString());
                    builder.Append("\r\n");
                }

                builder.Append("\r\n\r\n**********\r\n\r\n");

                Type t = typeof(DeviceStatus);

                PropertyInfo[] properties = t.GetProperties();

                foreach (PropertyInfo property in properties)
                {
                    builder.AppendFormat("{0}:\t{1}", property.Name, property.GetValue(null, null));
                    builder.Append("\r\n");
                }

                return builder.ToString();
            }
        }

        public void Send()
        {

            client.UploadStringCompleted += client_UploadStringCompleted;
            client.UploadStringAsync(new Uri("http://www.zhaorong.me/omnia/feedback/" + TimeSpan + ".txt", UriKind.RelativeOrAbsolute), Content);
        }

        void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            client.UploadStringCompleted -= client_UploadStringCompleted;
            MessageBox.Show(e.Result, e.Error == null ? "" : e.Error.Message, MessageBoxButton.OK);
        }

        public static void WriteLog(string log)
        {
            Debug.WriteLine(log);

            try
            {
                using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                {

                    using (IsolatedStorageFileStream isoFileStream = isoFile.OpenFile("log.txt", FileMode.Append, FileAccess.Write))
                    using (StreamWriter sw = new StreamWriter(isoFileStream))
                    {
                        isoFileStream.Seek(0, SeekOrigin.End);
                        sw.WriteLine(DateTime.Now.ToString("\r\nyyyy-MM-dd HH:mm:ss\r\n") + log);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

        public static void WriteLog(LogInfo log)
        {
            Debug.WriteLine(log);

            try
            {
                XDocument document = new XDocument();
                XElement[] elements = new XElement[] { new XElement("time", log.Time), new XElement("type", log.Type), new XElement("message", log.Message), new XElement("trace", log.StackTrace) };
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists("log.xml"))
                    {
                        using (IsolatedStorageFileStream isoFileStream = store.OpenFile("log.xml", FileMode.Open, FileAccess.Read))
                        {
                            document = XDocument.Load(isoFileStream, LoadOptions.None);
                        }
                    }
                    else
                    {
                        document = new XDocument(new XElement("root"));
                        
                    }

                    document.Root.Add(new XElement("log", elements));

                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("log.xml", FileMode.Create, store))
                    {
                        document.Save(isoStream);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
    }

    public class LogInfo
    {
        public LogInfo()
        {
            Time = DateTime.Now;
        }

        public LogInfo(string type, string message, string stackTrace)
        {
            Time = DateTime.Now;
            Type = type;
            Message = message;
            StackTrace = stackTrace;
        }

        public LogInfo(string type, Exception ex)
        {
            Time = DateTime.Now;
            Type = type;
            Message = ex.Message;
            StackTrace = ex.StackTrace;
        }

        public DateTime Time { get; set; }
        public string Type { get; set; }
        public string Message { get; set; }
        public string StackTrace { get; set; }
    }
}
